// 1.移除数组 [1, 2, 3, 4, 2] 中的2。不要直接修改数组，结果返回新的数组
let a1 = [1, 2, 3, 4, 2];
function f1(arr, index) {
  return arr.filter((item) => item !== index);
}
console.log(f1(a1, 2));
console.log('a1', a1);

// 2.定义一个函数,能在数组 [1, 2, 3, 4, 2] 的 "2"后面添加元素 "JavaScript"。不要直接修改数组 arr，结果返回新的数组
let a2 = [1, 2, 3, 4, 2];
function f2(arr, element, value) {
  const newArray = [];
  for (let i = 0; i < arr.length; i++) {
    newArray.push(arr[i]);
    if (arr[i] === element) {
      newArray.push(value);
    }
  }
  return newArray;
}
console.log(f2(a2, 2, 'JavaScript'));
console.log('a2', a2);

// 3.统计数组 [1, 2, 3, 4, 2] 中2出现的次数
let arr3 = [1, 2, 3, 4, 2];
let sum = 0;
for (let i = 0; i < arr3.length; i++) {
  if (arr3[i] === 2) sum++;
}
console.log('sum', sum);

// 4.找出数组 [1, 2, 3, "JavaScript", 4, "JavaScript", 2, 4, "JavaScript"] 中重复出现过的元素,并用数组将重复元素装起来输出
let arr4 = [1, 2, 3, 'JavaScript', 4, 'JavaScript', 2, 4, 'JavaScript'];
let arr4_1 = [];
for (let i = 0; i < arr4.length; i++) {
  const element = arr4[i];
  if (arr4.indexOf(element, i + 1) !== -1 && arr4_1.indexOf(element) === -1) {
    arr4_1.push(element);
  }
}
console.log('arr4_1', arr4_1);

// 5.在数组里面输出年龄小于17的对象
let arr5 = [
  {
    name: '111',
    sex: 'boy',
    age: 18,
  },
  {
    name: '222',
    sex: 'girl',
    age: 17,
  },
  {
    name: '333',
    sex: 'boy',
    age: 16,
  },
  {
    name: '444',
    sex: 'girl',
    age: 15,
  },
  {
    name: '555',
    sex: 'boy',
    age: 20,
  },
];

let arr5_1 = [];
for (let i = 0; i < arr5.length; i++) {
  let element = arr5[i];
  if (arr5[i].age < 17) {
    arr5_1.push(arr5[i]);
  }
}
console.log('arr5_1', arr5_1);

// 6. 数组扁平化, 把数组[1, [2, [3, 4, 5]]]转成[1, 2, 3, 4，5]
let arr6 = [1, [2, [3, 4, 5]]];
let arr6_1 = arr6.flat(Infinity);
console.log('arr6_1', arr6_1);
// function fn6(arr) {
//   for (let i = 0; i < arr.length; i++) {
//     if (Array.isArray(arr[i])) {
//       fn6(arr[i]);
//     } else {
//       arr6_1.push(arr[i]);
//     }
//   }
// }
// fn6(arr6);

// 7. 使用reduce实现[1,2,3,4,9]数组中所有成员的和
let arr7 = [1, 2, 3, 4, 9];
let sum7 = arr7.reduce((acc, item) => sum + item, 0);
console.log(sum7);

// 8. 数组去重的方法 (4种)
let array = [1, 2, 2, 3, 4, 4, 5];

// Set方法
let arr1 = Array.from(new Set(array));
console.log(arr1); // 输出: [1, 2, 3, 4, 5]

//indexOf方法
let arr2 = [];
for (let i = 0; i < array.length; i++) {
  if (arr2.indexOf(array[i]) === -1) {
    arr2.push(array[i]);
  }
}
console.log(arr2); // 输出: [1, 2, 3, 4, 5]

//includes方法
const arrr3 = [];
for (let i = 0; i < array.length; i++) {
  if (!arrr3.includes(array[i])) {
    arrr3.push(array[i]);
  }
}
console.log(arrr3); // 输出: [1, 2, 3, 4, 5]

//reduce方法
const arrr4 = array.reduce((acc, current) => {
  if (acc.indexOf(current) === -1) {
    acc.push(current);
  }
  return acc;
}, []);
console.log(arrr4); // 输出: [1, 2, 3, 4, 5]
